package org.example.com.zwh.service;

import org.example.com.zwh.entity.Product;
import org.example.com.zwh.mapper.ProductStockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

// 新增商品库存服务类
@Service
public class ProductStockService {
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 原子操作数据库库存（每次减1）
    public boolean reduceStock(int stock, Long productId) {
        return productStockMapper.updateStock(stock, productId) > 0;
    }

    //获取所有库存
    public List<Product> getAllStocks() {

        return productStockMapper.getAllStocks();
    }

    //获取单个库存
    public int updateStock(Integer stock, Long id) {
        return productStockMapper.updateStock(stock, id);
    }
    /***
     * 对账库存
     * @param stock
     * @param id
     * @return
     */
    public int updateStockNow(Integer stock, Long id) {
        return productStockMapper.updateStockNow(stock, id);
    }
    //数据库同步redis库存
    public void syncStockToRedis() {
        List<Product> products = productStockMapper.getAllStocks();
        if (products == null) {
            throw new RuntimeException("库存操作失败");
        }
        products.forEach(product -> {
            String key = "seckill:stock:" + product.getId();
            Integer stock = (Integer) redisTemplate.opsForValue().get(key);
            if (stock == null) {
                //如果不存在，返回失败
                throw new RuntimeException("库存操作失败");
            }
            //使用hash存储商品库存
            redisTemplate.opsForHash().put("seckill:products", product.getId().toString(), product.getStock());
            //使用hash存储秒杀商品库存
            redisTemplate.opsForHash().put("seckill:stock", product.getId().toString(), product.getStock());

        });
    }
}
